import { _decorator, Component, Node, Prefab, instantiate, NodeEventType, v3, UITransform, Vec3, resources, SpriteFrame, ImageAsset, Sprite, Size, Label, BaseNode, director, Animation, Toggle } from 'cc';
import { Index } from './Index';
const { ccclass, property } = _decorator;

interface Wh {
    width: number
    height: number
}

interface Level {
    level: string
    title: string
}

@ccclass('Main')
export class Main extends Component {
    //规格3
    static guige: number = 3;
    static level: Level = {
        level: 'Levels/1',
        title: '第一关'
    };
    speed: number = 0;
    pos: Vec3;
    @property(Node)
    Alert: Node;
    alertShow: boolean = false;
    @property(Node)
    Pass: Node;
    @property(Label)
    PassTxt: Label;
    PassShow: boolean = false;
    @property(Node)
    Childrens: Node;
    poss: Array<Vec3> = [];
    @property(Prefab)
    Item: Prefab;
    @property(Label)
    Level: Label;
    @property(Label)
    Speed: Label;
    start() {
        this.init();
        console.log(Main.level);
    }
    update() {
        this.Level.string = String(Main.level.title);
        this.Speed.string = String(this.speed);
        this.Alert.active = this.alertShow;
        this.Pass.active = this.PassShow;
    }
    init() {
        const { x, y } = this.Childrens.getComponent(UITransform).contentSize;
        const wh: Wh = {
            width: (x / Main.guige),
            height: (y / Main.guige)
        };
        //如果已经有子节点了就清空所有子节点
        if (this.Childrens.children.length > 0) {
            this.Childrens.removeAllChildren();
        }
        for (let y = 0; y < Main.guige; y++) {
            for (let x = 0; x < Main.guige; x++) {
                const w: number = x * wh.width;
                const h: number = y * wh.height;
                //实例化预制体
                const node = instantiate(this.Item);
                //添加到Childrens节点下面
                this.Childrens.addChild(node);
                //设置img子节点宽高和Children一样
                resources.load(Main.level.level, ImageAsset, (err, data) => {
                    if (!err) {
                        node.children[0].getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(data);
                        node.children[0].getComponent(UITransform).setContentSize(this.Childrens.getComponent(UITransform).contentSize);
                    }
                })
                //设置img对应node位置
                node.children[0].setPosition(v3(-w, -h, 0));
                //设置node宽高和定位
                node.getComponent(UITransform).setContentSize(new Size(wh.width, wh.height));
                node.setPosition(v3(w, h, 0));
                //绑定单击事件
                node.on(NodeEventType.TOUCH_START, this.itemClick, this);
                //添加到标记里面去
                node.name = String(`${y}_${x}`);
            }
        }
        //指定右下角为空白
        let pos = v3(999, 999, 0);
        this.pos = pos;
        this.Childrens.children[2].children[0].setPosition(pos);
        //标记原始所有图片位置
        this.poss = JSON.parse(JSON.stringify(this.Childrens.children.map(item => item.children[0].position)));
        //打乱顺序
        this.random();
    }
    random() {
        const arrs: Array<Node> = [...this.Childrens.children];
        let ars: Array<Vec3> = [];
        //打乱顺序拿到ars里面
        while (arrs.length > 0) {
            let node = arrs[Math.floor(Math.random() * arrs.length)];
            if (ars.length > 0) {
                if (ars.indexOf(node.children[0].position) == -1) {
                    ars.push(node.children[0].position);
                    arrs.splice(arrs.indexOf(node), 1);
                }
            } else {
                ars.push(node.children[0].position);
                arrs.splice(arrs.indexOf(node), 1);
            }
        }
        //断开原数组的链接
        ars = JSON.parse(JSON.stringify(ars));
        this.Childrens.children.forEach((item, i) => item.children[0].setPosition(ars[i]));
    }
    //元素点击事件 
    itemClick({ target }) {
        let node: Node = target;
        let x = Number(node.name[2]);
        let y = Number(node.name[0]);
        let LR: Array<Node[]> = [];
        let jhpos: Function;
        let _this = this;
        // 按行分组
        jhpos = function (Img: Node) {
            let nodePos: Vec3 = JSON.parse(JSON.stringify(node.children[0].position));
            let ImgPos: Vec3 = JSON.parse(JSON.stringify(Img.children[0].position));
            node.children[0].setPosition(ImgPos);
            Img.children[0].setPosition(nodePos);
            _this.speed += 1;
        }
        for (let i = Main.guige; i <= (Main.guige * Main.guige); i += Main.guige) {
            LR.push(this.Childrens.children.slice(i - Main.guige, i));
        }
        try {
            // 向左
            // console.log('左', LR[y][x - 1].children[0].position);
            let pos: Vec3 = LR[y][x - 1].children[0].position;
            if (pos.x === this.pos.x && pos.y === this.pos.y) {
                jhpos(LR[y][x - 1]);
            }
        } catch (error) { }
        try {
            //向右
            // console.log('右', LR[y][x + 1].children[0].position);
            let pos: Vec3 = LR[y][x + 1].children[0].position;
            if (pos.x === this.pos.x && pos.y === this.pos.y) {
                jhpos(LR[y][x + 1]);
            }
        } catch (error) { }
        try {
            //向上
            // console.log('上', LR[y + 1][x].children[0].position);
            let pos: Vec3 = LR[y + 1][x].children[0].position;
            if (pos.x === this.pos.x && pos.y === this.pos.y) {
                jhpos(LR[y + 1][x]);
            }
        } catch (error) { }
        try {
            //向下
            // console.log('下', LR[y - 1][x].children[0].position);
            let pos: Vec3 = LR[y - 1][x].children[0].position;
            if (pos.x === this.pos.x && pos.y === this.pos.y) {
                jhpos(LR[y - 1][x]);
            }
        } catch (error) { }
        let bol = this.Childrens.children.every((item, i) => {
            let { x, y } = item.children[0].position;
            if (x === this.poss[i].x && y === this.poss[i].y) {
                return true;
            } else {
                return false;
            }
        })
        if (bol) {
            this.PassShow = true;
            let msg: string[] = ['你', '一', '共', '走', '了', `${this.speed}`, '步', '完', '成', '通', '关', '!'];
            let timeMsg = setInterval(() => {
                if (msg.length > 0) {
                    const node = this.PassTxt.getComponent(Label);
                    let oldmsg = node.string;
                    node.string = oldmsg + msg.shift();
                } else {
                    clearInterval(timeMsg);
                    console.log('完成打字机效果');
                }
            }, 200)
        }
    }
    //按钮点击事件
    onclick({ target }) {
        const node: BaseNode = target;
        if (node.getComponent(Animation)) {
            node.getComponent(Animation).play();
        }
        setTimeout(() => {
            switch (node.name) {
                case 'Stop':
                    this.alertShow = true;
                    break;
                case 'X':
                    this.alertShow = false;
                    break;
                case 'Reset':
                    this.speed = 0;
                    this.random();
                    this.alertShow = false;
                    break;
                case 'Exit':
                    director.loadScene('Index');
                    break;
                case 'Levels':
                    Index.Show = true;
                    director.loadScene('Index');
                    break;
                case 'Toggle':
                    let icon = 'icons/Voiced';
                    switch (node.getComponent(Toggle).isChecked) {
                        case true: icon = 'icons/Voiced'; break;
                        case false: icon = 'icons/Mute'; break;
                    }
                    resources.load(icon, ImageAsset, (err, ImgData) => {
                        if (!err) {
                            node.children[0].getComponent(UITransform).setContentSize(new Size(50, 50));
                            node.children[0].getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(ImgData);
                        }
                    })
                    break;
            }
        }, 500);
    }
}


